package com.example.springjms;

import java.io.Serializable;
import java.util.Map;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
@Service
public class JmsTempletService {
    @Autowired
	private JmsTemplate jmsTemplate;
	
	public void sendJms(String queueName,final Serializable Object ){
		jmsTemplate.send(new ActiveMQQueue(queueName), new MessageCreator() {
			
			@Override
			public Message createMessage(Session arg0) throws JMSException {
				// TODO Auto-generated method stub
				
				return arg0.createObjectMessage(Object);
			}
		});
	}
	public void sendJms(String queueName,final Map<String,Object> map ){
		jmsTemplate.send(new ActiveMQQueue(queueName), new MessageCreator() {
			
			@Override
			public Message createMessage(Session arg0) throws JMSException {
				// TODO Auto-generated method stub
				MapMessage message=arg0.createMapMessage();
				for(String key:map.keySet()){
					message.setObject(key, map.get(key));
				}
				return message;
			}
		});
	}
	
	
	public Object receive(String queueName){
		return jmsTemplate.receiveAndConvert(queueName);
	}
	
	public void sendTopic(String topicName,final Serializable object){
		jmsTemplate.send(new ActiveMQTopic(topicName), new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				// TODO Auto-generated method stub
				
				return session.createObjectMessage(object);
			}
		});
	}
	
	public Object receiveTopic(String topicName){
		 return jmsTemplate.receiveAndConvert(new ActiveMQTopic(topicName));
	}


}
